//
//  LogInViewController.m
//  ICard
//
//  Created by fanshao on 11-2-27.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "LogInViewController.h"
#import "constant.h"
#import "SBJSON.h"
#import "NSString+SBJSON.h"
#import "MyCard.h"
#import "UserInfo.h"
#import "InofTabbarContrller.h"


@implementation LogInViewController

@synthesize userNameTextField;
@synthesize passwordTextField;
@synthesize logInButton;
@synthesize forgotPasswordButton;

@synthesize receivedData, delegate;


// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	[userNameTextField setDelegate:self];
	[passwordTextField setDelegate:self];
	
	[self.userNameTextField setDelegate:self];
	self.userNameTextField.returnKeyType = UIReturnKeyDone;
	self.userNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
	[self.passwordTextField setDelegate:self];
	self.passwordTextField.returnKeyType = UIReturnKeyDone;
	self.passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}



- (void)dealloc {
	[userNameTextField release];
	[passwordTextField release];
	[logInButton release];
	[forgotPasswordButton release];
	[receivedData release];
    [super dealloc];
}

- (IBAction)logInSever:(id)sender{
	//NSString *text  = @"http://card.cd/icard/Login.json?acc=13588879256&pwd=000000";
	
	//if (!self.receivedData) {
	self.receivedData = [NSMutableData data];
	//}
	userName = @"13588879256";
	password = @"000000";
	
	NSString *requestStirng =[NSString stringWithFormat: @"acc=%@&pwd=%@", userName, password];
	NSData *postData = [NSData dataWithBytes:[requestStirng UTF8String] length:[requestStirng length]];
	
	
	
	NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[kLoginURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	[connectionRequest setHTTPMethod:@"POST"];
	[connectionRequest setTimeoutInterval:120.0];
	[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	[connectionRequest setHTTPBody:postData];
	
	NSURLConnection *connection = [[NSURLConnection alloc]
								   initWithRequest:connectionRequest
								   delegate:self];
	[connection autorelease];
	
}
- (IBAction)forgotPassword:(id)sender{
	
}

#pragma mark -
#pragma mark TextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField{
	
	CGRect rect1 = self.logInButton.frame;
	if (rect1.origin.y <320) {
		return;
	}
	rect1.origin = CGPointMake(rect1.origin.x, rect1.origin.y -216);
	[self.logInButton setFrame:rect1];
	
	CGRect rect2 = self.forgotPasswordButton.frame;
	rect2.origin = CGPointMake(rect2.origin.x, rect2.origin.y -216);
	[self.forgotPasswordButton setFrame:rect2];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
	[textField resignFirstResponder];
	CGRect rect1 = self.logInButton.frame;
	rect1.origin = CGPointMake(rect1.origin.x, rect1.origin.y +216);
	[self.logInButton setFrame:rect1];
	
	CGRect rect2 = self.forgotPasswordButton.frame;
	rect2.origin = CGPointMake(rect2.origin.x, rect2.origin.y +216);
	[self.forgotPasswordButton setFrame:rect2];
	return YES;
}

#pragma mark connection delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	
	[self.receivedData appendData:data];
	NSLog(@"self.reveivedData is %@", self.receivedData);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	
	NSString *temp = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding] ;
	NSLog(@"temp is %@", temp);
	NSNumber *number =  [[temp JSONValue]  valueForKey:@"rlt"] ;
	
	
	int ret = [number intValue];
	if (ret) {
		NSString *errorInfo = [[temp JSONValue] valueForKey:@"txt"];
		NSLog(@"errorInfo is %@",errorInfo);
		UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't log in!", nil)
														   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
		
		[alerView show];
		[alerView release];
		
	}
	else {
		NSArray *cardsArray = [[temp JSONValue] valueForKey:@"cards"];
		NSLog(@"the count is %d", [cardsArray count]);
		
		NSMutableArray *cardArray = [NSMutableArray array];
		for (NSDictionary *dict in cardsArray) {
			MyCard *myCard  = [[MyCard alloc] init];
			myCard.cardId = [dict objectForKey:@"cardid"];
			myCard.myname = [dict objectForKey:@"myname"];
			myCard.cardName = [dict objectForKey:@"cardname"];
			myCard.vcard = [dict objectForKey:@"vcard"];
			//myCard.head = [dict objectForKey:@"head"];
			myCard.last = [dict objectForKey:@"last"];
			myCard.mobile = [dict objectForKey:@"mobile"];
			[cardArray addObject:myCard];
		}
		NSString *pt = [[temp JSONValue] valueForKey:@"ppt"];
		[[UserInfo shardUserInfo] setPpt:pt];
		[[UserInfo shardUserInfo] setCardArray:cardArray];
		[[UserInfo shardUserInfo] savePref];
		//[pt release];
		//[cardsArray release];
		//[cardArray release];
		InofTabbarContrller *firstViewController = [[InofTabbarContrller alloc] init];
		if(firstViewController == nil)
			return;
		else
		{
			[firstViewController setTitle:@"我的名片"];
			[[self navigationController] pushViewController:firstViewController animated:YES];
			
		}
		[firstViewController release];

	}
	
}
- (void)didFailDownloadWithError:(NSError *)error {
	//[self stopAnimating];
	//[self processError:error];
	NSString *str = [error localizedDescription];
	UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:str
													   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
	
	[alerView show];
	[alerView release];
	
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[self didFailDownloadWithError:error];
	
	
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	BOOL disconnect = NO;
	//NSLog(@"Response, the statuscode is %d", [(NSHTTPURLResponse *)response statusCode]);	//[self setResponse:response];
	
	switch([(NSHTTPURLResponse *)response statusCode]) {
		case 200:
		case 206:
			break;
		case 304:
			disconnect = YES;
			break;
		case 400:
		{
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't get the Chinese name", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			disconnect = YES;
		}
			break;
			
			break;
			
		case 404:
		{
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't get the Chinese name", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			
			//[self connection:connection didFailWithError:theError];
			//[self stopAnimating];
			
			disconnect = YES;
		}
			break;
		case 416:
		{
			NSError *theError = [NSError errorWithDomain:@"CustomDomain"
													code:416 
												userInfo:[NSDictionary dictionaryWithObject:@"Range is missmatch."
																					 forKey:NSLocalizedFailureReasonErrorKey]];
			[self connection:connection didFailWithError:theError];
			[self stopAnimating];
			disconnect = YES;
		}
			break;
		case 403:
		case 401:
		case 500:
		{
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Server error Name Get", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			//[self stopAnimating];
		}
			break;
		default:
		{
			NSError *theError = [NSError errorWithDomain:@"CustomDomain"
													code:666
												userInfo:[NSDictionary dictionaryWithObject:@"Unknown error."
																					 forKey:NSLocalizedFailureReasonErrorKey]];
			[self connection:connection didFailWithError:theError];
		}
			disconnect = YES;
			break;
	}
	
}

@end
